package sm.hibernate.type;

import java.io.UnsupportedEncodingException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;

import sm.codec.CharacterCodec;

public class BlobArrayType extends AbstractArrayType {

	@Override
	public Type[] getPropertyTypes() {
		return new Type[] { Hibernate.BINARY };
	}

	@Override
	protected String getText(ResultSet rs, String[] names,
			SessionImplementor session, Object owner)
			throws HibernateException, SQLException {
		byte[] bytes = (byte[]) Hibernate.BINARY.nullSafeGet(rs, names,
				session, owner);
		String result = null;
		if (bytes != null) {
			try {
				result = new String(bytes, CharacterCodec.CHARSET);
			} catch (UnsupportedEncodingException e) {
				throw new HibernateException(e.getMessage(), e);
			}
		}
		return result;
	}

	@Override
	protected void setText(PreparedStatement st, Object value, int index,
			SessionImplementor session) throws HibernateException, SQLException {
		byte[] bytes = null;
		if (value != null) {
			String stringValue = (String) value;
			try {
				bytes = stringValue.getBytes(CharacterCodec.CHARSET);
			} catch (UnsupportedEncodingException e) {
				throw new HibernateException(e.getMessage(), e);
			}
		}
		Hibernate.BINARY.nullSafeSet(st, bytes, index, session);

	}

}
